// script.js  
const CAS = 'http://localhost:8080';
const BACKEND = 'http://localhost:8082';
const PARAMS = new URLSearchParams(window.location.search);

document.addEventListener('DOMContentLoaded', (event) => {  
	fetchAndRenderTeacher();
	fetchAndRenderSections();
});

function fetchAndRenderTeacher() {
	const apiUrl = `${BACKEND}/teacher/${localStorage.getItem("account")}`;  
	const teacherInfoContainer = document.getElementById('teacher-name');
	fetch(apiUrl, {
			credentials: "include"
		})
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch classes');  
	        }  
	        return response.json();  
	    })  
	    .then(data => {  
			teacherInfoContainer.innerHTML = data.name;  
	    })  
	    .catch(error => {  
	        console.error('Error fetching classes:', error);  
	    });  
}

function fetchAndRenderSections() {
	const apiUrl = `${BACKEND}/teacher/${localStorage.getItem("account")}/section`;  
	const classListContainer = document.getElementById('class-list');  	  
	fetch(apiUrl, {
		credentials: "include"
	})  
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch classes');  
	        }  
	        return response.json();  
	    })  
	    .then(data => {  
	        classListContainer.innerHTML = '';  
	        data.forEach(classInfo => {  
	            const listItem = document.createElement('li');  
	  
	            const className = document.createElement('h3');  
	            className.textContent = classInfo.section.id; // 假设数据对象有一个'name'属性  
	  
	            const classInfoParagraph = document.createElement('h3');  
	            classInfoParagraph.textContent = `${classInfo.course.name}`; // 假设数据对象有一个'studentsCount'属性  
				const classInfoParagraph2 = document.createElement('p');  
				classInfoParagraph2.textContent = `学期: ${classInfo.section.semester}`; // 假设数据对象有一个'studentsCount'属性  
	  
	            listItem.appendChild(className);  
	            listItem.appendChild(classInfoParagraph);  
				listItem.appendChild(classInfoParagraph2);  
				listItem.addEventListener('click', function() {  
					const sectionId = classInfo.section.id;
					const classPageUrl = `./section/index.html?section=${sectionId}`;
					window.location.href = classPageUrl;  
				});  
	  
	            classListContainer.appendChild(listItem);  
	        });  
	    })  
	    .catch(error => {  
	        console.error('Error fetching classes:', error);  
	    });  
}

const logoutBtn = document.getElementById('logoutBtn');
logoutBtn.addEventListener('click', ()=>{
	window.location.href = `${CAS}/logout-page`;
	localStorage.setItem('account', null);
	localStorage.setItem('token', null);
});